package com.ms.education.acl.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ms.education.R;
import com.ms.education.acl.entity.Role;
import com.ms.education.acl.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ms
 * @since 2023-02-18
 */
@RestController
@RequestMapping("/acl/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @SaCheckPermission("role.list")
    @ApiOperation("获取角色分页列表")
    @PostMapping("page/{current}/{limit}")
    public R page(@PathVariable("current") long current,
                  @PathVariable("limit") long limit,
                  @RequestBody Role role) {
        Page<Role> page = roleService.pageRole(current, limit, role);
        return R.ok().data("rows", page.getTotal())
                .data("roles", page.getRecords());
    }

    @SaCheckPermission("role.list")
    @ApiOperation("根据id获取角色")
    @GetMapping("get/{id}")
    public R get(@PathVariable("id") Integer id) {
        Role role = roleService.getById(id);
        return R.ok().data("role", role);
    }

    @SaCheckPermission("role.add")
    @ApiOperation("新增角色")
    @PutMapping("save")
    public R save(Role role) {
        roleService.save(role);
        return R.ok();
    }

    @SaCheckPermission("role.update")
    @ApiOperation("修改角色")
    @PostMapping("update")
    public R update(Role role) {
        roleService.updateById(role);
        return R.ok();
    }

    @SaCheckPermission("role.remove")
    @ApiOperation("删除角色")
    @PostMapping("delete")
    public R delete(@RequestBody Integer[] ids) {
        roleService.removeBatchByIds(Arrays.asList(ids));
        return R.ok();
    }

    @ApiOperation("获取用户角色和权限列表")
    @GetMapping("getRoleAndPermission/{userId}")
    public R getRoleAndPermission(@PathVariable("userId") Integer userId) {
        Map<String, Object> res = roleService.getRoleAndPermission(userId);
        return R.ok().data(res);
    }

    @SaCheckPermission("role.acl")
    @ApiOperation("获取用户角色")
    @GetMapping("getUserRole/{userId}")
    public R getUserRole(@PathVariable("userId") Integer userId) {
        List<Integer> roleIds = roleService.getUserRole(userId);
        return R.ok().data("roleIds", roleIds);
    }

    @ApiOperation("为用户赋予角色")
    @PostMapping("endowedUserRole/{userId}")
    public R endowedUserRole(@PathVariable("userId") Integer userId,
                             @RequestBody Integer[] roleIds) {
        roleService.endowedUserRole(userId, roleIds);
        return R.ok();
    }



}
